<template>
  <div class="report_list">
    <a-card :bordered="false" class="query_card">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8">
              <a-form-item label="报表名称">
                <a-input placeholder="请输入" v-model="queryParam.name" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8">
              <a-form-item label="说明">
                <a-input placeholder="请输入" v-model="queryParam.remark" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8" style="display: flex; justify-content: flex-end;">
              <a-button type="primary" @click="onSearch">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => this.queryParam = {}">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>

    <!-- 表格 -->
    <a-card style="margin-top: 10px;">
      <!-- 创建按钮 -->
      <div class="report_title">
        <span>报表列表</span>
        <a-button type="primary" class="set_up" @click="onSetUpReport" icon="plus" v-action:add="'report'">新建</a-button>
      </div>
      <a-table
        :columns="columns"
        :data-source="reportList"
        :pagination="currentConfig"
        :loading="table_loading"
        :scroll="{x: true}"
        @change="onTableHandle"
        rowKey="id"
      >
        <span slot="action" slot-scope="row">
          <a-row v-if="!row.shared">
            <a @click="onLookReport(row)">查看</a>
            <a-divider type="vertical"/>
            <a @click="openSharingModal(row)" v-if="!row.shared">内部分享</a>
            <a-divider type="vertical"/>
            <a @click="openPublicSharingModal(row)" v-if="!row.shared">公开分享</a>
            <a-divider type="vertical"/>
            <a-dropdown>
              <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                更多 <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item key="0">
                  <a @click="onConfigReport(row)" v-action:edit="'report'">配置</a>
                </a-menu-item>
                <a-menu-item key="1">
                  <a @click="onUpdateReport(row)" v-action:edit="'report'">编辑</a>
                </a-menu-item>
                <a-menu-item key="2">
                  <a @click="onCopyReport(row)" v-action:edit="'report'">复制</a>
                </a-menu-item>
                <a-menu-item key="3">
                  <a @click="onDeleteReport(row)" v-action:delete="'report'">删除</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </a-row>
          <a-row v-if="row.shared">
            <a @click="cancelSharing(row)" v-if="row.shared === true">取消分享</a>
            <a-divider type="vertical"/>
            <a @click="onCopyReport(row)" v-action:edit="'report'">复制</a>
            <a-divider type="vertical" v-action:edit="'report'"/>
            <a @click="onLookReport(row)">查看</a>
          </a-row>
        </span>
      </a-table>
    </a-card>

    <a-modal v-model="visible" :title="title" @ok="handleOk" :maskClosable="false" :confirmLoading="buttonLoading" class="modal_report">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        >
        <a-form-model-item v-show="form.templateReportId > 0" label="报表模板" prop="templateReportId">
          {{ templateReportName }}
        </a-form-model-item>
        <a-form-model-item label="报表名称" prop="name">
          <a-input v-model="form.name" placeholder="为报表起一个名字吧！" />
        </a-form-model-item>
        <a-form-model-item label="说明" prop="remark">
          <a-textarea v-model="form.remark" placeholder="为自己写下一些说明信息吧！" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <a-modal
      :title="addUserForm.title"
      :visible="addUserForm.visible"
      :confirm-loading="addUserForm.loading"
      :maskClosable="false"
      @ok="confirmSharing"
      @cancel="closeSharingModal"
    >
      <a-form-model
        ref="addUserForm"
        :model="addUserForm.data"
        :rules="addUserForm.rules"
        :layout="addUserForm.layout"
      >
        <!-- 角色名称 -->
        <a-form-model-item label="" prop="userIds">
          <a-select
            mode="multiple"
            placeholder="请选择用户"
            v-model="addUserForm.data.userIds"
            style="width: 100%"
          >
            <a-select-option v-for="(item,index) in allUsers" :key="item.id" :value="item.id" :disabled="item.disabled">
              {{ item.username }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <public-sharing-modal
      v-bind:visible="publicSharing.visible"
      v-bind:report-obj="publicSharing.reportObj"
      v-on:closePublicSharingModal="closePublicSharingModal"

    >
    </public-sharing-modal>
  </div>


</template>

<script>
import {mapActions, mapMutations, mapState} from 'vuex';
import {baseMixin} from '@/store/app-mixin';
import PublicSharingModal from "@/views/reportForms/components/publicSharingModal";

const columns = [
  {
    title: '报表名称',
    dataIndex: 'name',
    sorter: true
  },
  {
    title: '说明',
    dataIndex: 'remark'
  },
  {
    title: '创建者',
    dataIndex: 'creatorName'
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    sorter: true
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    sorter: true
  },
  {
    title: '操作',
    fixed: 'right',
    scopedSlots: {customRender: 'action'},
  }
]

export default {
  components: {PublicSharingModal},
  mixins: [baseMixin],
  name: 'ReportList',
  data() {
    return {
      columns,
      queryParam: {},
      advanced: false,
      form: {
        templateReportId: 0,
        name: '',
        remark: ''
      },
      templateReportName: '',
      visible: false,
      buttonLoading: false,
      title: '创建报表',
      table_loading: false,
      rules: {
        name: [
          {required: true, message: '请输入报表名称', trigger: 'blur'},
          {max: 100, message: '最大长度限制为100个字符', trigger: 'blur'},
        ],
        remark: [
          {max: 255, message: '最大长度限制为255个字符', trigger: 'blur'}
        ]
      },
      addUserForm: {
        layout: 'vertical',
        title: '选择分享用户',
        visible: false,
        loading: false,
        data: {
          userIds: []
        },
        rules: {
          userIds: [
            {
              type: 'array',
              required: true,
              trigger: 'change',
              message: '请选择用户'
            }
          ]
        }
      },
      allUsers:[],
      publicSharing: {
        visible: false,
        reportObj: null
      }
    }
  },
  watch: {
    visible(val) {
      if (!val) {
        this.$refs.ruleForm && this.$refs.ruleForm.resetFields();
        this.form = {}
      }
    }
  },
  computed: {
    ...mapState('reportManage', ['reportList', 'currentConfig']),
  },
  mounted() {
    this.onLoadReportConfig()
  },
  beforeDestroy() {
    this.SET_SEARCH({name: null, remark: null})
  },
  methods: {
    ...mapMutations('reportManage', ['SET_CURRENT', 'SET_PAGES', 'SET_ORDER', 'SET_SEARCH']),
    ...mapMutations('custom', ['SET_REPORT']),
    ...mapActions('custom', ['setReport', 'updateReport']),
    ...mapActions('reportManage', ['getReportList', 'getUpdateReportList', 'deleteReportList',
      'sharingReport', 'cancelSharingReport', 'getReportUser'
    ]),
    ...mapActions('orgManage', ['getAllUsersList']),
    // 保存报表
    handleOk() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.buttonLoading = true
          if (this.form.id) {
            this.updateReport({...this.form})
              .then(res => {
                this.visible = false
                this.getReportList()
                this.$message.success('报表编辑成功！')
              })
              .catch(err => {
                this.$message.error('报表修改失败，原因：' + err.msg + '！')
              })
              .finally(_ => {
                this.buttonLoading = false
              })
          } else {
            this.setReport({...this.form})
              .then(res => {
                this.visible = false
                this.getReportList()
                this.$message.success('报表创建成功！')
              })
              .catch(err => {
                this.$message.error('报表创建失败，原因：' + err.msg + '！')
              })
              .finally(_ => {
                this.buttonLoading = false
              })
          }
        } else {
          setTimeout(() => {
            this.form.loadingBtn = false
            this.form.statusBtn = false
            return false
          }, 1500)
        }
      })
    },
    // 创建
    onSetUpReport() {
      this.form.templateReportId = 0
      this.templateReportName = ''
      this.title = '创建报表'
      this.visible = true
    },
    //复制报表
    onCopyReport(row) {
      this.form.templateReportId = row.id
      this.templateReportName = row.name
      this.title = "基于模板创建报表"
      this.visible = true
    },
    order_way(order) {
      if (order == 'ascend') {
        return 'asc'
      } else if (order == 'descend') {
        return 'desc'
      } else {
        return ''
      }
    },
    // 分页-每页条数
    onTableHandle(page, filters, {field, order}) {
      const orderObj = {
        order: this.order_way(order),
        orderBy: field || ''
      }
      this.SET_CURRENT(page.current)
      this.SET_PAGES(page.pageSize)
      this.SET_ORDER({...orderObj})
      this.getReportList()
    },
    onConfigReport(row) {
      this.getUpdateReportList({id: row.id})
        .then((res) => {
          this.SET_REPORT({...res.data})
          this.form = {...res.data}
          this.$router.push({name: 'ReportConfig', params: {report: {...res.data}}, query: {id: row.id}})
        })
    },
    // 获取修改行
    onUpdateReport(row) {
      this.form.templateReportId = 0
      this.templateReportName = ''
      this.title = '编辑报表'
      this.visible = true
      this.getUpdateReportList({id: row.id})
        .then((res) => {
          this.SET_REPORT({...res.data})
          this.form = {...res.data}
          // this.$router.push({ name:'ReportConfig', params:{ report: {...res.data} } })
        })
        .catch((err) => this.$message.error('获取修改报表信息失败，原因：' + err.msg + '！'))
    },
    // 获取删除行
    onDeleteReport(row) {
      this.getReportUser(row.id).then(res => {
        let content = '删除报表后无法恢复，您确定要继续吗？'
        if (res && res.length > 0){
          content = '报表已被分享给其他用户，删除后所有用户都将无法查看此报表数据，您确定要继续吗？'
        }
        this.$confirm({
          title: '删除提示',
          content: content,
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            this.deleteReportList(row.id)
              .then(() => {
                this.getReportList()
                this.$message.success('报表删除成功')
              })
              .catch((err) => this.$message.error('报表删除失败，原因：' + err.msg + '！'))
          },
          onCancel: () => {},
        })
      })

    },
    onLookReport(row) {
      this.$router.push({path: "/system/show_reports/" + row.id, params: {id: row.id}})
    },
    onSearch() {
      this.SET_SEARCH({...this.queryParam})
      this.getReportList()
    },
    // 展开收起
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    // 初始化加载页面数据
    onLoadReportConfig() {
      this.table_loading = true;
      this.getReportList()
        .then(res => {
        })
        .catch(err => {
          if (err.code == 401) {
            this.err401(err)
            return
          }
          this.$message.error('获取报表列表失败，原因：' + err.msg + '！')
        })
        .finally(res => {
          this.table_loading = false;
        })
    },
    openPublicSharingModal(row) {
      this.publicSharing.visible = true
      this.publicSharing.reportObj = row
    },
    closePublicSharingModal(){
      this.publicSharing.visible = false
      this.publicSharing.reportObj = null
    },
    openSharingModal(row){
      this.getReportUser(row.id).then(res => {
        const userIds = []
        for (let i in res){
          userIds.push(res[i].id)
        }
        this.addUserForm.data.userIds = userIds
      })
      this.getAllUsersList().then(res => {
        this.allUsers = res
      })
      this.addUserForm.data.reportId = row.id
      this.addUserForm.visible = true
    },
    closeSharingModal(){
      this.addUserForm.visible = false
      this.addUserForm.loading = false
      this.addUserForm.data.userIds = []
    },
    confirmSharing(){
      this.$refs.addUserForm.validate(valid => {
        if (valid) {
          this.addUserForm.loading = true;
          let userIds = this.addUserForm.data.userIds
          let userIdStr = ""
          if (userIds && userIds.length > 0){
            userIdStr = userIds.join(",")
          }
          let params = {
            orgId: this.selectedOrgId,
            userIds: userIdStr,
            reportId: this.addUserForm.data.reportId
          }
          this.sharingReport(params)
            .then(res => {
              this.$message.success('添加用户成功')
              this.closeSharingModal()
            }).catch(error => {
              console.error(error)
              this.$message.error('添加用户失败，原因：' + error.msg)
          }).finally(()=>{
            this.addUserForm.loading = false
          })
        }
      })
    },
    cancelSharing(row) {
      this.$confirm({
        title: '取消分享',
        content: '取消分享后，将不能再查看该数据看板，那你确定要继续吗?',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          this.cancelSharingReport(row.id)
            .then(() => {
              this.getReportList()
              this.$message.success('取消分享成功')
            })
            .catch((err) => this.$message.error('取消分享失败，原因：' + err.msg + '！'))
        },
        onCancel: () => {
        },
      })
    }
  }
}
</script>

<style scoped>
.report_list {
  width: 100%;
  height: 100%;
}
.set_up{
  float: right;
}

.query_card >>> .ant-card-body {
  padding: 24px 24px 0px 24px;
}

.ant-drawer>>>.ant-drawer-body{
  height: calc(100% - 55px);
}

.ant-form{
  height: 100%;
  display: flex;
  flex-direction: column;
}

.submit_style{
  margin-bottom: 0;
  flex: 1;
}

.submit_style>>>.ant-col.ant-col-18.ant-form-item-control-wrapper{
  width: 100%;
  height: 100%;
}

.submit_style>>>.ant-form-item-control{
  display: flex;
  height: 100%;
  align-items: flex-end;
}

.submit_style>>>span.ant-form-item-children{
  width: 100%;
}

.save_button,
.cancal_button {
  float: right;
}

.cancal_button {
  margin-right: 15px;
}

.report_title{
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}


.report_title span {
  display: block;
  float: left;
  margin-bottom: 0;
  padding-right: 12px;
  color: rgba(0,0,0,.85);
  font-size: 16px;
  font-weight: 500;
  line-height: 32px;
}


.ant-table-wrapper>>>td.ant-table-row-cell-break-word {
  padding: 10px;
}

.search_form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.search {
  display: flex;
  align-items: center;
  margin-left: 10px;
  margin-top: 10px;
}

.search input {
  flex: 1;
}

.search_label {
  min-width: 70px;
  text-align: right;
}

.search_button{
  display: flex;
  flex: 1;
  justify-content: center;
  align-items: center;
}

.search_button button {
  margin-right: 5px;
}

.collapse_row{
  width: 100%;
  position: relative;
}

.collapse_row2 {
  width: 100%;
}

.search_area {
  position: absolute;
  right: 0;
  bottom: 50%;
  transform: translate(0, 50%);
}

.collapse{
  display: flex;
  align-items: center;
  height: 50px;
  background-color: #fff;
  margin-bottom: 10px;
  flex-wrap: wrap;
}

span.ant-calendar-picker{
  width: 100%;
}

.ant-row.ant-form-item>>>.ant-col.ant-form-item-label {
  width: 78px;
}

.report_list>>>ul.ant-pagination.ant-table-pagination {
  width: 100%;
  display: flex;
}

.report_list>>>ul.ant-pagination.ant-table-pagination>li.ant-pagination-total-text {
  flex: 1;
  font-size: 14px;
  color: #999;
  text-indent: 10px;
}

.modal_report form.ant-form-horizontal >>>.ant-form-item {
  display: flex;
}

.modal_report form.ant-form-horizontal >>>.ant-form-item-control-wrapper{
  flex: 1;
}

</style>
